package cn.com.anypay.manager.controller.auth;

import cn.com.anypay.manager.common.controller.BaseController;
import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.common.validation.ValidationGroups;
import cn.com.anypay.manager.dto.request.SmsLoginRequest;
import cn.com.anypay.manager.service.LoginAuthService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class LoginAuthController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(LoginAuthController.class);

    @Resource
    private LoginAuthService loginAuthService;

    @PostMapping("/sms/send")
    public ApiResponse<String> sendSmsCode(
            @RequestBody @Validated(ValidationGroups.Login.class) SmsLoginRequest.SendCodeRequest request) {
        log.info("=== SMS验证码发送请求开始 ===");
        log.info("请求参数: {}", request);

        try {
            boolean success = loginAuthService.sendSmsCode(request);
            if (success) {
                log.info("SMS验证码发送成功: phone={}", request.getPhone());
                return success("验证码发送成功");
            } else {
                log.warn("SMS验证码发送失败: phone={}", request.getPhone());
                return fail("验证码发送失败");
            }
        } catch (Exception e) {
            log.error("SMS验证码发送异常: ", e);
            return fail("发送验证码失败: " + e.getMessage());
        } finally {
            log.info("=== SMS验证码发送请求结束 ===");
        }
    }

    @PostMapping("/sms/verify")
    public ApiResponse<Object> verifySmsCode(
            @RequestBody @Validated(ValidationGroups.Login.class) SmsLoginRequest.VerifyCodeRequest request) {
        log.info("=== SMS验证码验证请求开始 ===");
        log.info("请求参数: {}", request);

        try {
            Map<String, Object> result = loginAuthService.verifySmsCode(request);
            if ((Boolean) result.get("success")) {
                log.info("SMS验证码验证成功: phone={}", request.getPhone());
                return success("验证成功", result.get("data"));
            } else {
                log.warn("SMS验证码验证失败: phone={}, message={}", request.getPhone(), result.get("message"));
                return fail((String) result.get("message"));
            }
        } catch (Exception e) {
            log.error("SMS验证码验证异常: ", e);
            return fail("验证码验证失败: " + e.getMessage());
        } finally {
            log.info("=== SMS验证码验证请求结束 ===");
        }
    }
}
